package com.cn.daifaming.demoservice.common.utils;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** 
 * 分装一个http请求的工具类
 * 
 * @author dWX384900
 */
public class HttpClientUtil
{
    
    private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
    
    /**
     * 初始化HttpClient
     */
    private static CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    
    /**
     * POST方式调用
     * 
     * @param url
     * @param params
     * @return 响应字符串
     * @throws IOException 
     * @throws java.io.UnsupportedEncodingException
     */
    public static String executeByPOST(String url, String params)
        throws IOException
    {
        HttpPost post = new HttpPost(url);
        
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseJson = null;
        try
        {
            if (params != null)
            {
                post.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
            }
            post.addHeader("Content-type", "application/json; charset=utf-8");
            post.setHeader("Accept", "application/json");
            
            log.info("post is {} and responseHandler is {}", post, responseHandler);
            responseJson = httpClient.execute(post, responseHandler);
            log.info("HttpClient POST请求结果：" + responseJson);
        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
            log.info("HttpClient POST请求异常：" + e.getMessage());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            httpClient.close();
        }
        return responseJson;
    }
}